import requests
from xml.etree import ElementTree as ET


def get_bluetooth_address_by_sn(bar_code, endpoint="http://localhost:8887/services/GZJDDeviceServices"):
    """
    通过设备序列号获取蓝牙地址

    :param bar_code: 设备条码/序列号
    :param endpoint: 服务端点URL
    :return: 蓝牙地址字符串，如果失败返回None
    """
    # SOAP请求XML模板
    soap_request = f"""
    <soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ser="http://service.jgmes.com/">
        <soapenv:Header/>
        <soapenv:Body>
            <ser:GetBluetoothAddressBySN>
                <barCode>{bar_code}</barCode>
            </ser:GetBluetoothAddressBySN>
        </soapenv:Body>
    </soapenv:Envelope>
    """

    # 设置请求头
    headers = {
        "Content-Type": "text/xml",
        "SOAPAction": "urn:GetBluetoothAddressBySN"
    }

    try:
        # 发送POST请求
        response = requests.post(endpoint, data=soap_request, headers=headers)
        response.raise_for_status()  # 检查HTTP错误

        # 解析XML响应
        root = ET.fromstring(response.content)

        # 使用XPath查找数据，注意命名空间
        namespaces = {
            'soap': 'http://schemas.xmlsoap.org/soap/envelope/',
            'ns1': 'http://service.jgmes.com'
        }

        # 检查是否成功
        is_success = root.find('.//ns1:isSuccess', namespaces)
        if is_success is not None and is_success.text.lower() == 'true':
            data = root.find('.//ns1:data', namespaces)
            if data is not None:
                return data.text
        else:
            # 可以添加错误处理逻辑
            error_code = root.find('.//ns1:errorCode', namespaces)
            message = root.find('.//ns1:message', namespaces)
            print(f"请求失败: 错误码={error_code.text if error_code is not None else '无'}, "
                  f"消息={message.text if message is not None else '无'}")
            return None

    except requests.exceptions.RequestException as e:
        print(f"HTTP请求失败: {e}")
        return None
    except ET.ParseError as e:
        print(f"XML解析失败: {e}")
        return None


# 使用示例
if __name__ == "__main__":
    # 测试设备条码
    bar_code = "VG0015-BO0200349"
    bluetooth_address = get_bluetooth_address_by_sn(bar_code)

    if bluetooth_address:
        print(f"设备 {bar_code} 的蓝牙地址是: {bluetooth_address}")
    else:
        print("获取蓝牙地址失败")